package com.langsin.my0628;

import com.langsin.bean.User;
import com.langsin.guochunrui.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author 郭春瑞
 */
public class gcrTest {
    @Test
    public void testCache1() throws Exception{
        //mybatis一级缓存是存在SQL Session的内存map里的
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory=builder.build(stream);
        SqlSession sqlSession=sessionFactory.openSession();
        //查询第一次
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user =userMapper.queryById(702);
        System.out.println(user);

        try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();}

        //同一个sqlsession 查询第二次
        User user2 =userMapper.queryById(702);
        System.out.println(user2);

    }
    //二级缓存
    //二级缓存需要序列化
    @Test
    public void testCache2() throws Exception{
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory=builder.build(stream);
        SqlSession sqlSession1=sessionFactory.openSession();
        //第一个会话
        UserMapper mapper1=sqlSession1.getMapper(UserMapper.class);
        User user1=mapper1.queryById(702);
        System.out.println(user1);
        sqlSession1.close();

        try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();}
        System.out.println("休眠一下");


        //第二个会话
        SqlSession sqlSession2=sessionFactory.openSession();
        UserMapper mapper2=sqlSession2.getMapper(UserMapper.class);
        User user2=mapper2.queryById(702);
        System.out.println(user2);
        sqlSession2.close();


    }
}
